<?php
/**
 * Created by PhpStorm.
 * User: 墨鱼行
 * Signature: 好好学习，天天向上
 * Date: 19-3-4
 * Time: 下午6:02
 */

namespace app\api\validate;


use think\Validate;

class OrderValidate extends BaseValidate
{
    protected $rule = [
        'products' => 'checkProducts'
    ];

    protected $singleRule = [
        'product_id' => 'require|isPositiveInteger',
        'count'      => 'require|isPositiveInteger'
    ];

    public function __construct ($method)
    {
        switch ($method)
        {
            case 'placeOrder':
                $this->rule = [
                    'products' => 'checkProducts'
                ];
                break;
            case 'delivery':
            case 'detail':
                $this->rule = [
                    'orderId' => 'isPositiveInteger'
                ];
                $this->message = [
                    'orderId' => '订单ID需要正整数'
                ];
                break;
            case 'getListByUser':
                $this->rule = [
                    'page'  => 'require|isPositiveInteger',
                    'limit' => 'require|isPositiveInteger',
                ];
                $this->message = [
                    'page' => '页码一定要非空正整数',
                    'limit' => '每页获取的条数一定要为非空正整数'
                ];
                break;
        }
    }

    /**
     * @param $values
     * @return bool
     * @throws \app\lib\exception\ThrowError
     */
    protected function checkProducts($values)
    {
        $values = is_array($values) ? $values : json_decode($values, true);

        if (empty($values))
        {
            T(601000);
        }

        foreach ($values as $value)
        {
            self::checkProductsArr($value);
        }

        return true;
    }

    /**
     * @param $value
     * @throws \app\lib\exception\ThrowError
     */
    private function checkProductsArr($value)
    {
        $validate = new BaseValidate();
        $value = is_array($value) ? $value : json_decode($value, true);
        $result = $validate->check($value, $this->singleRule);

        if (empty($result))
        {
            T(100000, ['field' => '需要为正整数']);
        }
    }
}